// Package ctxkit 操作请求 ctx 信息
package ctxkit

import (
	"context"
	"gfrest/web/app/model"
	"time"

	"github.com/gogf/gf/net/ghttp"
)

// WithUser 注入 User
func WithUser(r *ghttp.Request, val model.AuthUser) *ghttp.Request {
	r.SetCtxVar("User", val)
	return r
}

// GetUser 获取当前请求 User
func GetUser(ctx context.Context) model.AuthUser {
	val, ok := ctx.Value("User").(model.AuthUser)
	if ok {
		return val
	}
	return model.AuthUser{}
}

// WithReqID 注入 ReqId
func WithReqID(r *ghttp.Request, val string) *ghttp.Request {
	r.SetCtxVar("ReqId", val)
	return r
}

// GetReqID 获取当前请求 ReqId
func GetReqID(ctx context.Context) string {
	val, ok := ctx.Value("ReqId").(string)
	if ok {
		return val
	}
	return "null"
}

// WithUserName 注入 UserName
func WithUserName(r *ghttp.Request, val string) *ghttp.Request {
	r.SetCtxVar("UserName", val)
	return r
}

// GetUserName 获取当前请求 UserName
func GetUserName(ctx context.Context) string {
	val, _ := ctx.Value("UserName").(string)
	return val
}

// WithReqStartTime 注入 ReqStartTime
func WithReqStartTime(r *ghttp.Request) *ghttp.Request {
	val := time.Now()
	r.SetCtxVar("ReqStartTime", val)
	return r
}

// GetReqStartTime 获取当前请求 ReqStartTime
func GetReqStartTime(ctx context.Context) time.Time {
	val, ok := ctx.Value("ReqStartTime").(time.Time)
	if ok {
		return val
	}
	return time.Now()
}

// WithUserID 注入 UserId
func WithUserID(r *ghttp.Request, val int64) *ghttp.Request {
	r.SetCtxVar("UserId", val)
	return r
}

// GetUserID 获取当前登录用户 ID
func GetUserID(ctx context.Context) int64 {
	uid, ok := ctx.Value("UserId").(int64)

	if ok {
		return uid
	}
	return -1
}

// WithUserIP 注入 UserIp
func WithUserIP(r *ghttp.Request, val string) *ghttp.Request {
	r.SetCtxVar("UserIp", val)
	return r
}

// GetUserIP 获取用户 IP
func GetUserIP(ctx context.Context) string {
	ip, ok := ctx.Value("UserIp").(string)
	if ok {
		return ip
	}
	return "null"
}
